import { ref } from 'vue'
import { defineStore } from 'pinia'
import { spuDetail } from '@/api/spuApi.js';
import { skuPage } from '@/api/skuApi.js';


export const useGoodStore = defineStore('good', () => {
	const showPage = ref(false);
	const detail = ref([])
	const currentSku = ref({}); // 当前选中的SKU数据
	const attribute = ref([]);
	const specList = ref([])
	const skuList = ref([])

	const HGetDetail = async (spuId, skuId) => {
		const spuReq = spuDetail({ id: spuId })
		const skuReq = skuPage({ spuId, current: 1, size: 500 })

		const [res1, res2] = await Promise.all([spuReq, skuReq])
		detail.value = res1.data
		specList.value = JSON.parse(res1.data.specList)

		skuList.value = res2.data.records
			.map(item => {
				item.specStr = item.spec.map(spec => {
					return spec.value
				}).join(',')

				return item
			})
		if (skuId) {
			currentSku.value = skuList.value.find(item => item.id === skuId)
		} else {
			currentSku.value = skuList.value[0]
		}

		showPage.value = true
	};

	return {
		detail,
		currentSku,
		attribute,
		specList,
		skuList,
		showPage,
		HGetDetail
	}
})